import { Component, Input, OnInit, ViewChild } from '@angular/core';
import { SFSchema } from '@delon/form';
import { ApiService } from '@core/services/api';
import { HttpClient } from '@angular/common/http';
import { NzMessageService, NzModalRef } from 'ng-zorro-antd';
import { UtilService } from '@core/services/util.service';
import { ColumnType, SPage, TablePageComponent } from '@shared/components/table-page/table-page.component';
import { NzTabPosition } from 'ng-zorro-antd/tabs';
import { Router } from '@angular/router';

@Component({
  selector: 'landlor-edit',
  templateUrl: './landlor-edit.component.html',
  styles: []
})
export class LandlorEditComponent implements OnInit {
    //房间信息列表
    @ViewChild('st', { static: false }) st: TablePageComponent;
    //用户信息
    @Input()type: 0 | 1;
    @Input()
    set _param(value) {
      console.log(value);
      if (!value) return;
      this.param = value;
      this.param.infoAge=this.analyzeIDCard(this.param.papersNumber);
      this.param.infoBirthday=this.getBirthdayFromIdCard(this.param.papersNumber);
      this.param.infoMobile = value.mobile
      if(this.param.infoPeoplePhoto) {
        this.previewImage = this.param.infoPeoplePhoto;
        this.fileList = [...[{
          id: '-1',
          status: 'done',
          url: this.param.infoPeoplePhoto
        }]]
      }

    };
    searchValue:any="";
    previewImage: string | undefined = '';
    previewVisible = false;
    param: any;
    showForm = false;
    fileList: any[] = [
      {
        id: '-1',
        status: 'done',
        url: "../../../../../assets/images/noimg.png"
      }
    ];
    houseList = [];
    schema: SFSchema = {
      properties: {
        approveStatus: {
          type: 'string',
          title: '审批状态',
          enum:[
            {label: '未审批', value: "1"},
            {label: '已审批', value: "0"}
          ],
          ui: {
            widget: 'select',
            grid:{span: 8}
          }
        },
        infoName: {
          type: 'string',
          title: '姓名',
          ui: {
            grid: {span: 8}
          }
        },
        papersNumber: {
          type: 'string',
          title: '身份证号',
          ui: {
            grid: {span: 8}
          }
        },
        infoSex: {
          type: 'string',
          title: '性别',
          enum:[
            {label: '女', value: "0"},
            {label: '男', value: "1"},
            {label: '未说明的性别', value: "9"}
          ],
          ui: {
            widget: 'select',
            grid: {span: 8}
          }
        },
        infoAge :{
          type: 'number',
          title: '年龄',

          ui: {
            grid: {span: 8}
          }
        },
        infoBirthday :{
          type: 'string',
          title: '出生日期',
          ui: {
            grid: {span: 8}
          }
        },
        // infoNationCode: {
        //   type: 'string',
        //   title: '民族代码',
        //   ui: {
        //     grid: {span: 6}
        //   }
        // },
        infoNationName: {
          type: 'string',
          title: '民族',
          ui: {
            grid: {span: 8}
          }
        },
        infoMobile: {
          type: 'string',
          title: '联系电话',
          ui: {
            grid: {span: 8}
          }
        },
        // infoEmergencyMobile: {
        //   type: 'string',
        //   title: '紧急联系电话',
        //   ui: {
        //     grid: {span: 8}
        //   }
        // },
        // idCardList2: {
        //   type: 'string',
        //   title: '现居住地址'
        // },
        papersAddress: {
          type: 'string',
          title: '身份证地址'
        }
      },
      "ui": {
        "spanLabelFixed": 150,
        "grid": {
          "span": 24
        }
      },
      //required: ['infoName', 'infoMobile']
    }
  
    handlePreview = async () => {
      this.previewVisible = true;
    };
  
    getUserInfo(userId: string): Promise<any>{
      return this.http.request<any>('GET', '/core/person/'+userId).toPromise();
    }
    
    formSubmit(data) {
    }
    constructor(
      private api: ApiService,
      private http: HttpClient,
      private msg: NzMessageService,
      private modalRef: NzModalRef,
      private util:UtilService,
      private router: Router,
    ) { }
  
    nzTabPosition: NzTabPosition = 'left';
  
    ngOnInit() {
      this.showForm = true;
      this.getlandlordManageUnitList();
    }

    selectChage($event){
      console.log($event);
      this.router.navigateByUrl("/house-manage");
    }

    getlandlordManageUnitList() : void{
      this.http.post(this.api.manager.landlordManageUnitList.url,{personId:this.param.personId}).subscribe((res:any) => {
        console.log(res)
        if (res.status === '200' && res.data && res.data.length > 0) {
          let list=[];
          for(let item of res.data){
            list.push({
              key:item.id,
              pId:"",
              title:item.addressName,
              id:item.id,
              value:item.id
            })
            for(let current of item.roomList){
              list.push({
                key:current.id,
                pId:current.areaId,
                title:current.roomNumber == 0 ? current.roomName : ""+current.roomNumber,
                id:current.id,
                value:current.id
              })
            }
          }
          console.log(this.util.getTreeNodeOption(list));
          this.houseList=this.util.getTreeNodeOption(list);
        } else {
          this.msg.error(res.message)
        }
      })
    }
      
      

/**
 * 根据身份证号精确计算年龄
 */
 analyzeIDCard(IDCard:any):Number{
	//获取用户身份证号码
	var userCard = IDCard;
	//如果身份证号码为undefind则返回空
	if(!userCard){
		return;
	}
	//获取出生年月日
	//userCard.substring(6,10) + "-" + userCard.substring(10,12) + "-" + userCard.substring(12,14);
	var yearBirth = userCard.substring(6,10);
	var monthBirth = userCard.substring(10,12);
	var dayBirth = userCard.substring(12,14);
	//获取当前年月日并计算年龄
	var myDate = new Date();
	var monthNow = myDate.getMonth() + 1;
	var dayNow = myDate.getDay();
	var age = myDate.getFullYear() - parseInt(yearBirth);
  monthNow=Number(monthNow);
  monthBirth = parseInt(monthBirth);
  dayNow=Number(dayNow);
  dayBirth=Number(dayBirth);

	if(monthNow < monthBirth || (monthNow == monthBirth && dayNow < dayBirth)){
		age--;
	}
	//返回年龄
	return age;
}
//计算生日
getBirthdayFromIdCard(idCard:any):string {
  var birthday = "";
  if(idCard != null && idCard != ""){
    if(idCard.length == 15){
      birthday = "19"+idCard.substr(6,6);
    } else if(idCard.length == 18){
      birthday = idCard.substr(6,8);
    }
    birthday = birthday.replace(/(.{4})(.{2})/,"$1-$2-");
  }
  return birthday;
}

}
  